package com.HomeWorkhsp.Chapter08.encap;

/**
 * Enjoy programming!!!
 * Time: 2021/11/16 -  20:19
 */
public class Encapsulation01 {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("jack你好吗");
        person.setAge(30);
        person.setSalary(30000);

        System.out.println(person.info());

        Person smith = new Person("smith", 2000, 50000);
        System.out.println("========smith的信息==========");
        System.out.println(smith.info());
    }
}
class Person{
    public String name;
    private int age;
    private double salary;

    //快捷键alt + fn + insert


    public Person() {
    }

    public Person(String name, int age, double salary) {
//        this.name = name;
//        this.age = age;
//        this.salary = salary;
        //可以将set方法放在构造器中，仍然可以验证
        setName(name);
        setSalary(salary);
        setAge(age);
    }

    public void setName(String name){
        //加入对数据的校验
        if(name.length() >= 2 && name.length() <= 6)
        this.name = name;
        else{
            System.out.println("名字的长度不对，需要（2-6）个字符，默认名字");
            this.name = "无名人";
        }
    }
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age >= 1 && age <= 120)//如果合理范围
        this.age = age;
        else{
            System.out.println("年龄需要在 1-120");
            this.age = 18;//给一个默认年龄
        }
    }

    public double getSalary() {
        //可以这里增加对当前对象的权限判断
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String info() {
        return "信息为 name=" + name + " age=" + age + " 薪水=" + salary;
    }
}
